package com.example.fashionshoes.message;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.example.fashionshoes.pojo.dto.OrderDTO;
import com.example.fashionshoes.pojo.po.Goods;
import com.example.fashionshoes.pojo.po.Order;
import com.example.fashionshoes.pojo.po.User;
import com.example.fashionshoes.service.GoodsService;
import com.example.fashionshoes.service.OrderService;
import com.example.fashionshoes.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class receiveMessage {
    @Resource
    private OrderService orderService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private UserService userService;
    @RabbitListener(queues = "queue.direct")
    @Transactional
    public void executeOrder(Message message){
        Object parse = JSON.parse(message.getBody());
        OrderDTO orderDTO = BeanUtil.copyProperties(parse, OrderDTO.class);
        String number = orderDTO.getNumber();
        String totalNum = orderDTO.getTotalNum();
        if (number.isBlank()) {
            return;
        }
        //修改订单状态
        orderService.lambdaUpdate().set(Order::getStatus, 2).eq(Order::getNumber, number).update();
        //扣减库存
        List<Order> orderList = orderService.lambdaQuery().eq(Order::getNumber, number).list();
        for (Order orderDB : orderList) {
            goodsService.lambdaUpdate().setSql("stock = stock-1").eq(Goods::getId,orderDB.getGoodsId()).update();
        }
        //给用户增加积分
        userService.lambdaUpdate().set(User::getScore,totalNum).eq(User::getId,orderList.getFirst().getUserId()).update();
    }
}
